<!--流水线号生成 cresated by ycr 2023.11.14-->
<template>
  <div class="list-card-container">
    <a-card title="流水号生成管理" class="general-card">
      <!-- 查询表单 -->
      <table-search
        ref="searchRef"
        :data-source="SEARCH_FORM"
        @change="searchFile"
      />
      <div>
        <a-button type="primary" style="margin-bottom: 10px" @click="openDrawer"
          >新增</a-button
        >

        <a-modal
          :visible="visible"
          title="新增流水线规则"
          :width="820"
          @cancel="closeDrawer"
          @ok="addSerialNum"
        >
          <a-spin :loading="loading">
            <a-form ref="formRef" :model="form" :style="{ width: '700px' }">
              <a-row :gutter="24">
                <a-col>
                  <a-form-item
                    label="流水线生成常用规则: "
                    field="serialCommonRule"
                    readonly
                  >
                    代号-年（月、日）-编号，例如 850-CJ-20231211-001<br />
                    (850-CJ为代号，20231211为日期，001为编号)
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item
                    label="流水号名称"
                    field="serialName"
                    :rules="[{ required: true, message: '请输入代号规则' }]"
                  >
                    <a-input v-model="form.serialName" />
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item
                    label="代号"
                    field="serialHead"
                    :rules="[{ required: true, message: '请输入代号规则' }]"
                  >
                    <a-input v-model="form.serialHead" />
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item
                    name="serialDate"
                    label="日期规则"
                    field="serialDate"
                    has-feedback
                    :rules="[
                      {
                        required: true,
                        message: '请选择年月日输入规则',
                      },
                    ]"
                  >
                    <a-select
                      v-model="form.serialDate"
                      :options="timeOptions"
                      placeholder="请选择年月日输入规则,yyyy代表年，MM代表月,dd代表日"
                    />
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-form-item
                    label="规定编号位数"
                    field="serialOrder"
                    :rules="[{ required: true, message: '请规定编号位数' }]"
                  >
                    <a-select
                      v-model="form.serialOrder"
                      :options="NumOptions"
                      placeholder="请选择编号位数，几个零代表编号占几位，如00，代表编号为两位"
                    />
                  </a-form-item>
                </a-col>
                <!-- <a-col>
                  <a-form-item
                    name="timeRule"
                    label="自定义常量"
                    field="serialConstRule"
                    has-feedback
                  >
                    <a-input v-model="form.serialConstRule" />
                  </a-form-item>
                </a-col> -->
                <a-col>
                  <a-form-item
                    label="流水号规则为："
                    field="serialRule"
                    readonly
                  >
                    {{ form.serialHead }}-{{ form.serialDate }}-{{
                      form.serialOrder
                    }}
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-spin>
        </a-modal>
      </div>
      <!--新增按钮-->
      <!-- <AddDrawer
        clickword="新增"
        title="新增流水线"
        narrow
        :data-source="ADD_SERIAL_NUMBER"
        style="margin-bottom: 16px"
        @change="addSerialNum"
      /> -->
      <a-table
        :columns="COLUMNS_FILE"
        :data="serialNumList"
        row-key="id"
        :pagination="pagination"
        :loading="loading"
        :scroll="{ x: 1000 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 插槽-操作 -->
        <template #operation="{ record }">
          <a-space>
            <!-- <a-link type="text" @click="showEditDrawer(record)"> 修改 </a-link> -->
            <a-popconfirm
              content="确定禁用吗?"
              type="warning"
              @ok="disableTbData(record.id)"
            >
              <a-link type="text" :disabled="record.reservedFields2 !== '1'"
                >禁用</a-link
              >
            </a-popconfirm>
            <a-popconfirm
              content="确定启用吗?"
              type="warning"
              @ok="enableTbData(record.id)"
            >
              <a-link type="text" :disabled="record.reservedFields2 === '1'"
                >启用</a-link
              >
            </a-popconfirm>
          </a-space>
        </template>
        <!-- 插槽-处理状态 -->
        <template #reservedFields2="{ record }">
          <a-tag v-if="record.reservedFields2 === '0'" color="gray">禁用</a-tag>
          <a-tag v-else-if="record.reservedFields2 === '1'" color="green"
            >已启用</a-tag
          >
        </template>
      </a-table>
    </a-card>
    <!-- 修改抽屉 -->
    <!-- <AdvancedDrawer
      ref="editDrawerRef"
      click="link"
      title="修改流水号规则"
      clickword=""
      :narrow="true"
      :rules="advancedDrawerRules"
      :data-source="editDrawerConfig"
      :data-record="currentRecord"
      @change="editDrawerSubmit"
    /> -->
  </div>
</template>

<script lang="ts" setup>
  import { Message, Notification, TableColumnData } from '@arco-design/web-vue';
  import { onMounted, ref, reactive } from 'vue';

  import { Pagination } from '@/types/global';
  import TableSearch from '@/common/components/cac-components/advanced-search/index.vue';
  // import AddDrawer from '@/common/components/cac-components/advanced-drawer/index.vue';
  // import { computed } from 'vue';
  import {
    NewSerialNumberData,
    SerialDetailParams,
    formConfig,
    SerialNumberId,
  } from '@/api/infrastructure/model/serialNumberGenerate';
  import {
    saveNewSerialNum,
    getSerialNumberList,
    disableSerialNumber,
    enableSerialNumber,
  } from '@/api/infrastructure/serial-number-generate';
  // import AdvancedDrawer from '@/common/components/cac-components/advanced-drawer/index.vue';

  const searchRef = ref<any>();
  const loading = ref<boolean>(false);
  // const editDrawerRef = ref<any>();
  // const currentRecord = ref<SerialDetailRecord>(); // 记录当前选择的表格行
  const visible = ref<boolean>(false); // 新增对话框是否可见
  const openDrawer = () => {
    visible.value = true;
  };
  const closeDrawer = () => {
    // console.log('关闭对话', form.value);
    form.value.serialName = '';
    form.value.serialConstRule = '';
    form.value.serialHead = '';
    form.value.serialOrder = '';
    form.value.serialDate = '';
    visible.value = false;
  };
  // setup() {
  //   const areas = [
  //     {label: '年月日', value: 'yyyyMMdd'},
  //     {label: '年月', value: 'yyyyMM'},
  //     {label: '月日', value: 'MMdd'},
  //     {label: '日月年', value: 'ddMMyyyy'},
  //     {label: '月日年', value: 'MMddyyyy'},
  //   ]
  // };
  const timeOptions = [
    { label: 'yyyyMMdd', value: 'yyyyMMdd' },
    { label: 'yyyyMM', value: 'yyyyMM' },
    { label: 'MMdd', value: 'MMdd' },
    { label: 'ddMMyyyy', value: 'ddMMyyyy' },
    { label: 'MMddyyyy', value: 'MMddyyyy' },
  ];
  const NumOptions = [
    { label: 'XX（两位编号）', value: 'XX' },
    { label: 'XXX（三位编号）', value: 'XXX' },
    { label: 'XXXX（四位编号）', value: 'XXXX' },
    { label: 'XXXXX（五位编号）', value: 'XXXXX' },
    { label: 'XXXXXX（六位编号）', value: 'XXXXXX' },
  ];
  const form = ref<formConfig>({
    serialName: '',
    serialHead: '',
    serialDate: '',
    serialOrder: '',
    serialConstRule: '',
  });
  // 查询表单
  const SEARCH_FORM: any[] = [
    { fieldName: 'serialName', labelText: '流水号名称', type: 'text' },
    { fieldName: 'reservedFields1', labelText: '创建人', type: 'text' },
    { fieldName: 'userCode', labelText: '创建人工号', type: 'text' },
  ];
  const searchFile = async (params: SerialDetailParams) => {
    getSerialNumber(params);
  };
  // 抽屉新增配置
  // const ADD_SERIAL_NUMBER = computed(() => {
  //   return [
  //     {
  //       type: 'text',
  //       labelText: '创建人',
  //       required: true,
  //       fieldName: 'name',
  //       col: 24,
  //     },
  //     {
  //       type: 'text',
  //       labelText: '流水线规则',
  //       required: true,
  //       fieldName: 'serialrRule',
  //       col: 24,
  //     },
  //   ];
  // });
  // 修改抽屉配置项
  // const editDrawerConfig = [
  //   {
  //     type: 'text',
  //     labelText: '创建人',
  //     required: true,
  //     fieldName: 'reservedFields1',
  //     col: 24,
  //   },
  //   {
  //     type: 'text',
  //     labelText: '流水线名称',
  //     required: true,
  //     fieldName: 'serialName',
  //     col: 24,
  //   },
  //   {
  //     type: 'text',
  //     labelText: '代号',
  //     required: true,
  //     fieldName: 'serialHead',
  //     col: 24,
  //   },
  //   {
  //     type: 'select',
  //     labelText: '日期规则',
  //     required: true,
  //     fieldName: 'serialDate',
  //     options: timeOptions,
  //     col: 24,
  //   },
  //   {
  //     type: 'select',
  //     labelText: '编号位数',
  //     required: true,
  //     options: NumOptions,
  //     fieldName: 'serialOrder',
  //     col: 24,
  //   },
  // ];
  /**
   * @description 打开修改抽屉
   * @param record 当前选择的表格行数据
   */
  // const showEditDrawer = (record: SerialDetailRecord) => {
  //   currentRecord.value = record;
  //   editDrawerRef.value.showDrawer(); // 打开修改抽屉
  // };
  // 表格
  const serialNumList = ref<NewSerialNumberData[]>([]);
  const COLUMNS_FILE: TableColumnData[] = [
    {
      title: '流水号名称',
      dataIndex: 'serialName',
      width: 100,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '创建人',
      dataIndex: 'reservedFields1',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '创建人工号',
      dataIndex: 'userCode',
      width: 150,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '流水号规则',
      dataIndex: 'serialNumber',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '是否启用',
      dataIndex: 'reservedFields2',
      width: 100,
      ellipsis: true,
      tooltip: true,
      slotName: 'reservedFields2',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      slotName: 'operation',
      width: 200,
      align: 'center',
      fixed: 'right',
    },
  ];
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // func: 查询数据源配置
  const getSerialNumber = async (params?: SerialDetailParams) => {
    loading.value = true;
    try {
      const { data } = await getSerialNumberList({
        limit: pagination.pageSize,
        page: pagination.current,
        ...params,
      });
      // console.log('data', data);
      // data.list.forEach(
      //   (e: {
      //     serialRule: string;
      //     serialHead: string;
      //     serialDate: string;
      //     serialOrder: string;
      //   }) => {
      //     e.serialRule = `${e.serialHead}-${e.serialDate}-${e.serialOrder}`;
      //     // console.log('e.serialRule', e.serialRule);
      //   }
      // );
      serialNumList.value = data.list;
    } finally {
      loading.value = false;
    }
  };
  // 抽屉表单项校验配置
  // const advancedDrawerRules = ref({
  //   createName: [{ required: true, message: '请输入创建人工号' }],
  //   serialOrder: [{ required: true, message: '请输入流水号生成规则' }],
  // });
  /**
   * @method
   * @description 新增流水线
   */
  const addSerialNum = async () => {
    const req = {
      serialName: form.value.serialName,
      serialHead: form.value.serialHead,
      serialOrder: form.value.serialOrder,
      serialDate: form.value.serialDate,
    };
    // console.log('新增流水线req', req);
    try {
      await saveNewSerialNum(req);
      Message.success('新增成功');
      visible.value = false;
    } finally {
      getSerialNumber();
    }
  };
  onMounted(() => {
    getSerialNumber();
  });
  /**
   * @method
   * @description 提交修改流水线
   */
  // const editDrawerSubmit = async (reqdata: any) => {
  //   try {
  //     await saveNewSerialNum(reqdata); // 目前调用的新增流水线接口
  //     Message.success('新增成功');
  //   } finally {
  //     getSerialNumber();
  //   }
  // };
  const disableTbData = async (params: SerialNumberId) => {
    try {
      const res = (await disableSerialNumber(params)) as any;
      // console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '禁用成功！',
        });
        getSerialNumber();
      } else {
        Notification.error({
          title: '禁用失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  const enableTbData = async (params: SerialNumberId) => {
    // console.log('id', params);
    try {
      const res = (await enableSerialNumber(params)) as any;
      // console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '启用成功！',
        });
        getSerialNumber();
      } else {
        Notification.error({
          title: '启用失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
</script>

<style lang="less" scoped>
  .list-card-container {
    padding: 20px;
    border-radius: var(--border-radius-default);
  }
</style>
